<template>
	<view class="container flex-c">
		<uni-nav-bar class="ch-nav" height="88rpx" backgroundColor="#FFFFFF" leftWidth="180rpx" rightWidth="180rpx" color="#333333" :fixed="true" :padding="false" @clickLeft="goBack()" @clickRight="$goByName('tradelist')">
			<template slot="left">
				<image class="left" src="@/public/images/public/dhl_fhjt.png" mode="aspectFit"></image>
			</template>
			<text class="title">充值</text>
			<template slot="right">
				<text class="text-primary">充值记录</text>
			</template>
		</uni-nav-bar>
		<view class="head flex-c ac">
			<text class="bean text-bold">{{user.chBean}}</text>
			<text class="text-secondary mt20">我的余额（彩虹豆）</text>
		</view>
		<view class="body">
			<view class="award flex-r ac" v-if="noticeText">
				<image class="notice-icon" src="@/public/images/user/tz.png" mode="aspectFit"></image>
				<uni-notice-bar class="notice-text" scrollable :text="noticeText" background-color="#FFF2D9" color="#B27936" :speed="80"></uni-notice-bar>
			</view>
			<view class="recharge flex-r ac jsb">
				<text class="recharge-money">充值金额</text>
				<text class="recharge-bean">1元=1彩虹豆</text>
			</view>
			<view class="money flex-c">
				<view class="list flex-r jsb">
					<view class="item-card flex-c ac jc" v-for="(item, index) in rechargeRule" :key="item.id" :class="{'active': active && item.id == active.id}" @tap="choose(item)">
						<view class="badge flex-r" v-if="item.awardValue">
							<text class="text-mini">+{{item.awardValue / item.ruleValue * 100}}%</text>
						</view>
						<text class="text-secondary">{{item.ruleValue+item.awardValue}}彩虹豆</text>
						<text class="text-mini color-grey">售价：{{item.ruleValue}}</text>
					</view>
				</view>
				<view class="list other-box flex-r">
					<view class="item-card other flex-c ac jc" @tap="otherChoose()" :class="{'active': other}">
						<view class="input-box flex-r ac jc">
							<text class="text-primary">¥</text>
							<input class="input text-primary" v-show="other" type="number" :focus="other" :maxlength="5" v-model="money" @input="inputMoney" @blur="blur">
							<text class="info text-small color-grey" v-show="!other">充值金额</text>
						</view>
					</view>
					<view class="item-card bean flex-r ac jc">
						<text>当前充值金额可兑换</text>
						<text class="color-red">{{money ? money + sendBean : 0}}</text>
						<!-- <text class="color-red">{{money ? sendBean : 0}}</text> -->
						<text>彩虹豆</text>
					</view>
				</view>
			</view>
			<view class="pay flex-c">
				<text class="title">支付方式</text>
				<radio-group @change="selectPay">
					<!-- <template v-for="(item,index) in payment">
						<view class="list-item flex-r ac" :key="index" v-if="item.payType.indexOf('ALI') > -1 || (platform == 'H5' && item.payType.indexOf('JSAPI') == -1) || (platform == 'JSAPI' && item.payType.indexOf('JSAPI') > -1)">
							<image class="item-icon" :src="item.channelLogo" mode="heightFix"></image>
							<text class="item-title text-primary">{{item.channelName}}</text>
							<view class="item-radio">
								<radio :value="item.payType" :checked="item.payType==payChannel" color="#0055FF"/>
							</view>
						</view>
					</template> -->
					<template v-if="payment">
						<view class="list-item flex-r ac">
							<image class="item-icon" :src="payment[0].channelLogo" mode="heightFix"></image>
							<text class="item-title text-primary">{{payment[0].channelName}}</text>
							<view class="item-radio">
								<radio :value="payment[0].payType" :checked="payment[0].payType==payChannel" color="#0055FF"/>
							</view>
						</view>
					</template>
				</radio-group>
			</view>
			<view class="agreement text-small flex-r ac">
				<image v-show="!isAgree" src="@/public/images/user/cz_wxz.png" class="radio" @tap="selectAgree"></image>
				<image v-show="isAgree" src="@/public/images/user/cz_xz.png" class="radio"></image>
				<text class="color-grey" @tap="selectAgree">我已阅读并接受</text>
				<text class="color-blue" @tap="$CHS.goAbout('recharge')">《彩虹体育用户购买协议》</text>
				<text class="color-blue" @tap="$CHS.goAbout('privacy')">《隐私政策》</text>
			</view>
			<view class="notice flex-c">
				<text class="title text-regular">温馨提示</text>
				<view class="content text-small color-grey">
					<text>1.彩虹体育</text>
					<text class="color-blue">非购彩平台</text>
					<text>，彩虹豆</text>
					<text class="color-blue">只用于购买专家方案，不支持提现等操作。</text>
				</view>
				<view class="content text-small color-grey">
					<text>2.购买后账户余额长时间没变化，请及时联系微信公众号：</text>
					<text class="color-blue">彩虹有料</text>
					<text>，我们将第一时间为您解决。</text>
				</view>
			</view>
		</view>
		<view class="foot flex-c">
			<view class="foot-toast flex-r ac jc">
				<text class="text-mini color-blue">彩虹豆只可用于购买专家料，不支持提现、购彩等操作</text>
			</view>
			<view class="foot-btn text-primary flex-r ac jsb">
				<text class="title">充值金额：</text>
				<text class="color-red">￥ {{ rechargePrice }}</text>
				<button type="default" :class="{'active': rechargePrice > 0}" size="mini" @tap="createOrder">
					立即充值
				</button>
			</view>
		</view>
		<view class="full-screen" :style="windowHeight" v-if="rechargeSuccess">
			<view class="recharge-popup flex-c">
				<view class="popup-head flex-r ac jsb">
					<text class="info"></text>
					<text class="title">充值成功</text>
					<view class="info right" @tap="closePopup()">
						<image src="@/public/images/public/qxan.png" mode="aspectFit"></image>
					</view>
				</view>
				<view class="popup-body flex-c ac">
					<image src="@/public/images/public/zfcg.png" mode="aspectFit"></image>
					<text class="result-text">恭喜您，充值成功！</text>
					<text class="text-secondary color-grey mt20">赶快去解锁你要解锁的方案吧！</text>
					<button class="unlock-btn text-large color-white" @tap="closePopup(lastRead.id)" v-if="lastRead.id">点击去解锁</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				money: undefined,
				other: false,
				isAgree: false,
				
				noticeText: null,
				chargeAward: null,
				rechargeRule: null,
				active: null,
				payment: null,
				payChannel: null,
				platform: null,
				rechargeSuccess: false,
				height: 0,
				
				lastRead: {} ,//最后浏览料
				rechargeRewards:[],//充值奖励
			}
		},
		computed: {
			user() {
				return this.$store.state.user
			},
			rechargePrice() {
				return this.active ? this.active.ruleValue : (!this.money ? 0 : this.money)
			},
			sendBean() {
				return this.active ? this.active.awardValue : this.getSendBean(this.money)
			},
			isMobile(){
				if(window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)) {
					return true
				}else{
					return false
				}
			},
			windowHeight() {
				return `--window-height:${this.height}px;`;
			}
		},
		onLoad(e) {
			let ua = navigator.userAgent.toLowerCase();
			if (ua.match(/micromessenger/i) == "micromessenger"){
				console.log(1);
				this.platform = 'JSAPI'
			}else{
				console.log(2);
				this.platform = 'H5'
			}
			this.getUserRule()
			this.getPayment()
			//请求用户最新信息
			this.$store.dispatch('updateUserinfo').catch((error)=>{
				console.log(error);
			});
			//查询浏览记录
			this.getLastReadArticle()
			//充值奖励
			this.getCharge_award()
		},
		onShow() {
			if(this.$Route.query.success === 1){
				let formdata = uni.getStorageSync('formdata')
				if(formdata){
					let out_trade_no = JSON.parse(formdata).out_trade_no
					this.checkOrderStatus(out_trade_no);
				}
			}else{
				this.checkHaveOrder()
			}
			this.height = uni.getSystemInfoSync().windowHeight
			this.windowResizeCallback = (res) => {
				this.height = res.size.windowHeight
			}
			uni.onWindowResize(this.windowResizeCallback)
		},
		onHide() {
			if(this.windowResizeCallback){
				uni.offWindowResize(this.windowResizeCallback)
				this.windowResizeCallback = null
			}
		},
		onUnload() {
			if(this.windowResizeCallback){
				uni.offWindowResize(this.windowResizeCallback)
				this.windowResizeCallback = null
			}
		},
		updated() {
			console.log('this.sendBean',this.active,this.getSendBean(this.money))
		},
		methods: {
			//判断浏览器
			checkUserAgent() {
				let ua = navigator.userAgent.toLowerCase();
				let platform = null
				if (ua.match(/micromessenger/i) == "micromessenger"){
					console.log(1);
					platform = 'JSAPI'
				}else{
					console.log(2);
					platform = 'H5'
				}
				return platform
			},
			//检查是否已有订单
			checkHaveOrder() {
				let haveOrder = uni.getStorageSync('haveOrder')
				if(haveOrder){
					//删除本地记录，防止重复提示
					uni.removeStorageSync('haveOrder')
					//formdata支付完成后通过返回URL参数获取，或者从本地存储获取
					let formdata = uni.getStorageSync('formdata')
					if(formdata){
						let out_trade_no = JSON.parse(formdata).out_trade_no
						uni.showModal({
							title: '支付提示',
							content: '查询到未支付订单，请确认是否已完成支付',
							confirmText: '已支付',
							cancelText: '未支付',
							success: (res) => {
								if(res.confirm){
									//验证支付结果
									this.checkOrderStatus(out_trade_no)
								}
							},
							complete: () => {
								uni.removeStorageSync('formdata')
							}
						})
					}
				}
			},
			//确认订单状态
			checkOrderStatus(orderNum) {
				this.$http.get({
					url: '/api/userRechargeRecord/verifyPayResult',
					data: {
						orderNum
					},
				}).then(data => {
					console.log(data,'datadata')
					if(data.success && data.code == 200 && data.result){
						console.log('验证通过后显示成功');
						this.$ShowToast({text: data.message || '恭喜您，充值成功！', type: 1})
						this.$store.dispatch('updateUserinfo')
						this.rechargeSuccess = true
					}else{
						uni.showModal({
							title: '支付提示',
							content: '您的充值支付未成功，如果您已完成支付，请联系公众号“彩虹有料”进行处理。',
							showCancel: false,
							success: () => {
								uni.setClipboardData({
									data: '彩虹有料'
								});
							}
						})
					}
					uni.removeStorageSync('formdata');
				}).catch((err) => {
					console.log(err);
				})
			},
			//关闭成功弹窗
			closePopup(articleId) {
				this.rechargeSuccess = false
				if(articleId){
					this.$Router.replace({name: 'articledetail', params: {aid: articleId, random: Date.now()}})
				}else{
					this.$CHS.rechargeSuccess(false)
				}
			},
			//选择充值金额
			choose(e) {
				this.active = e
				this.other = false
				this.money = e.ruleValue
			},
			//选择其他金额
			otherChoose() {
				uni.pageScrollTo({
					duration: 0,
					scrollTop: 10000
				})
				this.active = null
				this.other = true
			},
			blur(e) {
				if(e.target.value < 1){
					this.other = false
				}
			},
			//其他金额输入
			inputMoney(e){
				if(e.target.value < 1){
					uni.showToast({
						title: '充值金额不能小于1',
						icon: 'none'
					})
					this.$nextTick(()=>{
						this.money = undefined
					})
				}else if(e.target.value > 20000){
					uni.showToast({
						title: '充值金额不能大于20000',
						icon: 'none'
					})
					this.$nextTick(()=>{
						this.money = 20000
					})
				}else{
					this.$nextTick(()=>{
						this.money = parseInt(e.target.value)
					})
				}
			},
			//充值奖励
			getCharge_award(){
				this.$http.get({
					url:"/api/dict/info",
					data:{
						code:"charge_award"
					}
				}).then((data)=>{
					if(data.success&&data.result){
						console.log(data.success,'===')
						this.rechargeRewards=data.result.map((item)=>{
							return {
								name:item.name.split(',').map(Number),
								value:Number(item.value)
							}
						})
						this.rechargeRewards.sort((a, b) => {
						  const nameA = a.name[0];
						  const nameB = b.name[0];
						
						  if (nameA < nameB) {
						    return -1;
						  }
						  if (nameA > nameB) {
						    return 1;
						  }
						  return 0;
						});
					}
					
				})
			},
			//金额=>彩虹豆换算
			getSendBean(money){
				console.log(money,'money',this.rechargeRewards)
				// if(this.rechargeRule && money){
				// 	console.log(money,'money',this.rechargeRule)
				// 	if(parseInt(money) >= this.rechargeRule[this.rechargeRule.length - 1].ruleValue){
				// 		let rule = this.rechargeRule[this.rechargeRule.length - 1]
				// 		console.log(rule,'rule')
				// 		return parseInt(money * (rule.awardValue / rule.ruleValue)) 
				// 	}else{
				// 		let ruleIndex= this.rechargeRule.findIndex(item => parseInt(money) < item.ruleValue)
				// 		console.log(ruleIndex,'ruleIndex')
				// 		if(ruleIndex - 1 < 0){
				// 			return 0
				// 		}else{
				// 			let rule = this.rechargeRule[ruleIndex - 1]
				// 			if(rule){
				// 				return parseInt(money * (rule.awardValue / rule.ruleValue)) 
				// 			}else{
				// 				return 0
				// 			}
				// 		}
				// 	}
				// }else{
				// 	return 0
				// }
				if(this.rechargeRewards&&money){
					for (let i = 0; i < this.rechargeRewards.length; i++) {
						if(money<this.rechargeRewards[0].name[0]){
							return 0
						}else if (money >= this.rechargeRewards[i].name[0] && money <this.rechargeRewards[i].name[this.rechargeRewards[i].name.length - 1]) {
							return parseInt(money * this.rechargeRewards[i].value);
					    }else if(money>=this.rechargeRewards[this.rechargeRewards.length-1].name[this.rechargeRewards[this.rechargeRewards.length-1].name.length-1]){
							return parseInt(money * this.rechargeRewards[this.rechargeRewards.length-1].value)
						}
					}
					return money;
				}
			},
			//选择支付方式
			selectPay(e) {
				console.log(e.detail.value);
				this.payChannel = e.detail.value
			},
			//同意协议
			selectAgree() {
				console.log(1);
				this.isAgree = true
			},
			//统一下单
			createOrder() {
				if(this.rechargePrice < 1){
					uni.showToast({
						title: '充值金额不能小于1',
						icon: 'none'
					})
					return
				}
				if(!this.isMobile){
					uni.showModal({
						title: '充值提示',
						content: "暂不支持电脑网页，请使用手机浏览器充值",
						showCancel: false
					})
					return
				}
				if(!this.payChannel){
					uni.showToast({
						title: '请选择支付方式',
						icon: 'none'
					})
					return
				}
				if(!this.isAgree){
					uni.showToast({
						title: '请同意并勾选用户购买协议',
						icon: 'none'
					})
					return
				}
				//清理旧数据
				uni.removeStorageSync('isFromWx')
				uni.removeStorageSync('haveOrder')
				uni.removeStorageSync('orderModel')
				//组织数据，并跳转支付页面
				console.log(this.payChannel);
				let orderModel = {
					bean: this.active ? this.active.ruleValue : this.money,
					orderChannel: 'recharge',
					payChannel: this.payChannel,
					rechargePrice: this.rechargePrice,
					sendBean: this.sendBean,
					userId: this.user.userId,
				}
				console.log(orderModel);
				//let params = { orderModel }
				if(this.payChannel == 'ALI_WAP'){
					this.$Router.replace({name: 'alipay', params: { orderModel }})
					//this.$goByName('alipay', params)
				}else{
					this.$Router.replace({name: 'wxpay', params: { orderModel }})
					//this.$goByName('wxpay', params)
				}
			},
			//获取充值规则
			getUserRule() {
				this.$http.get({
					url: '/api/appUser/queryAppRuleRows',
					data: {
						type: 'recharge',
						userId: this.user.userId
					},
				}).then(data => {
					console.log(data.result,'data.result');
					if(data.success){
						this.rechargeRule = data.result.sort((a, b) => {
							return a.ruleValue - b.ruleValue
						})
						this.noticeText = data.data
					}else{
						console.log(data.message)
						this.navBack(data.message)
					}
				}).catch((err) => {
					console.log(err)
					this.navBack('充值数据请求错误，请稍候重试')
				})
			},
			//获取支付方式
			getPayment() {
				this.$http.get({
					url: '/api/appUser/queryPayChannel'
				}).then(data => {
					console.log(data.result,'===');
					if(data.success){
						this.payment = data.result
						
						if(!this.platform){
							this.platform = this.checkUserAgent()
						}
						this.$nextTick(()=>{
							if(this.payment.length == 1){
								this.payChannel = this.payment[0].payType
							}else{
								let payChannel = this.payment.find(item => item.payType.indexOf(this.platform) > -1)
								if(payChannel){
									this.payChannel = payChannel.payType
								}
							}
							console.log(this.payChannel,'this.payChannel');
						})
					}else{
						console.log(data.message)
						this.navBack(data.message)
					}
				}).catch((err) => {
					console.log(err)
					this.navBack('充值数据请求错误，请稍候重试')
				})
			},
			//获取最新浏览料
			getLastReadArticle() {
				this.$http.get({
					url: '/api/user/article/browse/record/newest'
				}).then((data)=>{
					console.log(data);
					if(data.success && data.result){
						this.lastRead = data.result
					}
				}).catch((err) => {
					console.log(err)
				})
			},
			//错误提示并返回
			navBack(message){
				uni.showModal({
					title: '错误提示',
					content: message,
					showCancel: false,
					success: (res) => {
						if(res.confirm){
							this.$Router.back(1)
						}
					}
				})
			},
			goBack(){
				let pages = getCurrentPages().length
				console.log(pages);
				if(pages > 1){
					this.$Router.back(1)
				}else{
					this.$Router.pushTab({name: 'userhome'})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		padding: 0;
		position: relative;
		.ch-nav{
			.text-primary{
				margin-right: 20rpx;
			}
		}
	}
	.head{
		margin: 20rpx 20rpx 0;
		padding: 75rpx 0;
		color: #FFFFFF;
		background: linear-gradient(225deg, #3377FF 0%, #0055FF 100%);
		background-size: 100%;
		border-radius: 10rpx 10rpx 0rpx 0rpx;
		.bean{
			font-size: 60rpx;
		}
	}
	.body{
		margin: 0 0 calc(168rpx + var(--safe-area-inset-bottom));
		.award{
			background-color: #FFF2D9;
			padding: 18rpx 20rpx;
			.notice-icon{
				width: 24rpx;
				height: 24rpx;
			}
			.notice-text{
				margin: 0;
				padding: 0 0 0 20rpx;
				/deep/ .uni-noticebar__content-wrapper--scrollable{
					height: 24rpx;
				}
				/deep/ .uni-noticebar__content-text{
					font-size: 24rpx;
					height: 24rpx;
					line-height: 1;
				}
			}
		}
		.recharge{
			padding:40rpx 20rpx 0rpx 20rpx;
			background-color: #FFFFFF;
			.recharge-money{
				font-weight: 500;
				color: #333333;
				font-size: 34rpx;
			}
			.recharge-bean{
				font-size: 24rpx;
				color: #999999;
			}
		}
		.money{
			background-color: #FFFFFF;
			padding: 20rpx 20rpx 30rpx;
			.title{
				font-size: 34rpx;
				font-weight: 600;
				line-height: 34rpx;
			}
			.list{
				flex-wrap: wrap;
				&.other-box{
					justify-content: flex-start;
					.item-card{
						margin-bottom: 0;
					}
				}
				.item-card{
					position: relative;
					width: 222rpx;
					height: 112rpx;
					background: #FFFFFF;
					border: 1px solid #CCCCCC;
					border-radius: 8rpx;
					box-sizing: border-box;
					margin-bottom: 20rpx;
					.text-secondary{
						font-weight: 500;
					}
					.text-mini{
						margin-top: 15rpx;
					}
					.badge{
						width: 64rpx;
						height: 38rpx;
						background-image: url("~@/public/images/user/bq5.png");
						background-size: 100%;
						border-radius: 0 8rpx 0 12rpx;
						background-repeat: no-repeat;
						position: absolute;
						top: -1px;
						right: -1px;
						text-align: right;
						justify-content: flex-end;
						.text-mini{
							margin-top: 6rpx;
							margin-right: 5rpx;
							font-weight: 500;
							color: #FFFFFF;
						}
					}
					&.other{
						padding: 0 30rpx;
					}
					&.bean{
						margin-left: 30rpx;
						width: 420rpx;
						border: none;
						justify-content: flex-start;
						color: #999999;
					}
					&.active{
						background: #0055FF;
						color: #FFFFFF;
						border: none;
						.text-mini{
							color: #FFFFFF;
						}
						.badge{
							top: 0;
							right: 0;
						}
					}
				}
				.input-box{
					font-size: 30rpx;
					.input, .info{
						margin-left: 20rpx;
					}
				}
			}
		}
		.pay{
			margin-top: 20rpx;
			padding: 40rpx 20rpx;
			background-color: #FFFFFF;
			.title{
				font-size: 36rpx;
				font-weight: 500;
			}
			.list-item{
				margin-top: 40rpx;
				.item-icon{
					margin-right: 30rpx;
					height: 56rpx;
					width: 56rpx;
				}
				.item-title{
					flex: 2;
				}
			}
		}
		.agreement{
			margin: 20rpx 20rpx 30rpx;
			.radio{
				width: 32rpx;
				height: 32rpx;
				margin-right: 10rpx;
			}
		}
		.notice{
			padding: 0 20rpx 30rpx;
			.title{
				font-weight: 500;
				margin-bottom: 20rpx;
			}
			.content{
				line-height: 40rpx;
			}
		}
	}
	.foot{
		max-width: $max-width;
		margin: $pc-margin;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #FFFFFF;
		padding-bottom: var(--safe-area-inset-bottom);
		.foot-toast{
			background: #E3EBFD;
			height: 48rpx;
		}
		.foot-btn{
			height: 120rpx;
			padding: 0 20rpx;
			.color-red{
				flex: 2;
			}
			button{
				width: 240rpx;
				height: 88rpx;
				line-height: 88rpx;
				background: #B2CCFF;
				border-radius: 44rpx;
				color: #FFFFFF;
				font-size: 32rpx;
				padding: 0;
				margin: 0;
				box-sizing: border-box;
				text{
					line-height: 88rpx;
				}
				&.active{
					background: #0055FF;
				}
			}
		}
	}
	.full-screen{
		z-index: 997;
		display: flex;
		flex-direction: column-reverse;
		overflow-x: scroll;
		height: var(--window-height);
		.recharge-popup{
			max-width: $max-width;
			margin: $pc-margin;
			margin-top: 126rpx;
			width: 100%;
			background: #FFFFFF;
			border-radius: 20rpx 20rpx 0 0;
			padding-bottom: var(--safe-area-inset-bottom);
			.popup-head{
				padding: 30rpx 20rpx;
				border-bottom: 1rpx solid #EDEDED;
				.title{
					font-size: 36rpx;
					font-weight: 500;
				}
				.info{
					width: 100rpx;
					font-size: 32rpx;
					&.right{
						text-align: right;
						image{
							width: 40rpx;
							height: 40rpx;
						}
					}
				}
			}
			.popup-body{
				margin: 80rpx 0;
				image{
					width: 320rpx;
					height: 200rpx;
				}
				.result-text{
					margin-top: 30rpx;
					font-size: 36rpx;
					font-weight: 500;
				}
				.unlock-btn{
					width: 280rpx;
					height: 96rpx;
					background: #0055FF;
					border-radius: 48rpx;
					border: none;
					padding: 0;
					margin: 40rpx 0 0 0;
					font-weight: 500;
					line-height: 96rpx;
				}
			}
		}
	}
</style>